<template>
    <s-layout title="新增订单">
        <view class="form-container">
            <uni-forms ref="formRef" :model="state.formData" :rules="rules" validate-trigger="bind">
                <uni-forms-item label="细胞产品" name="cellProductId" required>
                    <uni-data-select
                        v-model="state.formData.cellProductId"
                        :localdata="state.cellProductOptions"
                        @change="onCellProductChange"
                        placeholder="请选择细胞产品"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item label="细胞规格" name="cellSpecification" required>
                    <uni-data-select
                        v-model="state.formData.cellSpecification"
                        :localdata="state.specificationList"
                        placeholder="请选择细胞规格"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item label="是否拆分" name="isSplit">
                    <switch :checked="state.formData.isSplit" @change="state.formData.isSplit = $event.detail.value" style="transform:scale(0.7)"></switch>
                </uni-forms-item>
                <uni-forms-item label="袋/管数" name="bagCount" required>
                    <uni-number-box v-model="state.formData.bagCount" :min="1"></uni-number-box>
                </uni-forms-item>
                <uni-forms-item label="细胞总数" name="totalCells">
                    <uni-easyinput v-model="state.formData.totalCells" disabled placeholder="请输入细胞总数" />
                </uni-forms-item>
                <uni-forms-item label="细胞来源" name="cellOrigin" required>
                    <uni-data-select
                        v-model="state.formData.cellOrigin"
                        :localdata="state.cellOriginOptions"
                        placeholder="请选择细胞来源"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item label="来源备注" name="originRemark" v-if="state.formData.cellOrigin=='AUTOLOGOUS'">
                    <uni-easyinput v-model="state.formData.originRemark" placeholder="请输入自体的姓名＋身份证号"></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item label="使用时间" name="usageTime" required>
                    <uni-datetime-picker
                        type="datetime"
                        v-model="state.formData.usageTime"
                        placeholder="请选择使用时间"
                        :start="minUsageTime"
                        @change="onTimeChange"
                    />
                </uni-forms-item>
                <uni-forms-item label="预约数量" name="reservationQuantity" required>
                    <uni-number-box v-model="state.formData.reservationQuantity" :min="1"></uni-number-box>
                </uni-forms-item>
                <uni-forms-item label="使用人" name="userName">
                    <view class="flex-row">
                        <uni-easyinput
                            v-model="state.formData.userName"
                            placeholder="请输入使用人"
                            class="flex-1"
                        />
                        <button class="choose-btn" @click="showCustomerPopup">选择</button>
                    </view>
                </uni-forms-item>

                <uni-forms-item label="联系方式" name="userContact">
                    <uni-easyinput v-model="state.formData.userContact" placeholder="请输入使用人联系方式" />
                </uni-forms-item>

                <uni-forms-item label="签收人" name="signerName">
                    <uni-easyinput v-model="state.formData.signerName" placeholder="请输入签收人"></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item label="签收号码" name="signerContact">
                    <uni-easyinput v-model="state.formData.signerContact" placeholder="请输入签收人手机号"></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item label="订单备注" name="remark">
                    <uni-easyinput v-model="state.formData.remark"  placeholder="请输入订单备注，填写订单总价格等信息"></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item name="agreeProtocol" required>
                    <checkbox-group
                        @change="state.formData.agreeProtocol = $event.detail.value.length > 0"
                        style="display: flex; align-items: center; justify-content: center;"
                    >
                        <label style="display: flex; align-items: center;">
                            <checkbox :checked="state.formData.agreeProtocol" value="true" />
                            <text style="margin-left: 6px;">
                                我已阅读并同意
                                <text
                                    style="color: #2979ff; text-decoration: underline;"
                                    @click="onProtocol('委托协议')"
                                >
                                    《相关协议》
                                </text>
                            </text>
                        </label>
                    </checkbox-group>
                </uni-forms-item>
            </uni-forms>
        </view>

        <!-- 选择客户弹窗 -->
        <uni-popup ref="popupRef" type="bottom">
            <view class="popup-container">
                <view class="popup-title">选择客户</view>
                <scroll-view style="max-height: 400rpx;" scroll-y>
                    <view
                        v-for="item in state.customerList"
                        :key="item.id"
                        class="popup-item"
                        @click="selectCustomer(item)"
                    >
                        {{ item.customerName }}（{{ item.contactPhone }}）
                    </view>
                </scroll-view>
            </view>
        </uni-popup>

        <view class="fixed-bottom-bar">
            <button class="submit-btn ui-BG-Main-Gradient" @tap="submitForm">提交</button>
        </view>
    </s-layout>
</template>

<script setup>
import { reactive, ref, watch, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import ReservationRecordApi from '@/sheep/api/system/reservationRecord';
import SLayout from '@/sheep/components/s-layout/s-layout.vue';
import UniForms from '@/uni_modules/uni-forms/components/uni-forms/uni-forms.vue';
import UniFormsItem from '@/uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue';
import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
import UniNumberBox from '@/uni_modules/uni-number-box/components/uni-number-box/uni-number-box.vue';
import UniDatetimePicker from '@/uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue';
import DictApi from "@/sheep/api/system/dict";
import {closeAuthModal} from "@/sheep/hooks/useModal";
import CustomerApi from "@/sheep/api/customer/customer";

const formRef = ref(null);
const state = reactive({
    cellList:[],
    customerList:[],
    cellOriginOptions:[{
        value:'ALLOGENEIC',
        text:'不指定'
    },
        {
            value: 'AUTOLOGOUS',
            text:'自体'
        }
    ],
    specificationList:[],
    cellProductOptions:[],
    formData: {
        id:null,
        agentId: null,
        cellProductId: null,
        cellSpecification: '',
        isSplit: false,
        bagCount: 1,
        totalCells: '',
        cellOrigin: '',
        originRemark: '',
        usageTime: '',
        reservationQuantity: 1,
        userName: '',
        userContact: '',
        signerName: '',
        signerContact: '',
        remark: '',
        agreeProtocol: false,
    },
});

// 时间选择变化处理
const onTimeChange = (e) => {
    console.log('选择的时间:', e);
    state.formData.usageTime = e;
}

const popupRef = ref(null);
// 打开弹窗
const showCustomerPopup = () => {
    popupRef.value.open();
};
// 选中客户
const selectCustomer = (item) => {
    state.formData.userName = item.customerName;
    state.formData.userContact = item.contactPhone;
    popupRef.value.close();
};
// 将时间转换为毫秒数
const convertTimeToMilliseconds = (timeString) => {
    if (!timeString) return null;
    return new Date(timeString).getTime();
}

// 手动校验函数
const validateForm = () => {
    const formData = state.formData;
    // 校验细胞产品
    if (!formData.cellProductId) {
        sheep.$helper.toast('细胞产品不能为空');
        return false;
    }
    // 校验细胞规格
    if (!formData.cellSpecification) {
        sheep.$helper.toast('细胞规格不能为空');
        return false;
    }
    // 校验袋/管数
    if (!formData.bagCount || formData.bagCount < 1) {
        sheep.$helper.toast('袋（管）数不能为空');
        return false;
    }
    // 校验细胞来源
    if (!formData.cellOrigin) {
        sheep.$helper.toast('细胞来源不能为空');
        return false;
    }
    // 校验使用时间
    if (!formData.usageTime) {
        sheep.$helper.toast('使用时间不能为空');
        return false;
    }
    // 校验预约数量
    if (!formData.reservationQuantity || formData.reservationQuantity < 1) {
        sheep.$helper.toast('预约数量不能为空');
        return false;
    }
    // 校验协议同意
    if (!formData.agreeProtocol) {
        sheep.$helper.toast('请同意协议');
        return false;
    }
    return true;
}

// 准备提交的数据
const prepareSubmitData = () => {
    const submitData = { ...state.formData };
    // 将时间转换为毫秒数
    if (submitData.usageTime) {
        submitData.usageTime = convertTimeToMilliseconds(submitData.usageTime);
    }
    // 处理布尔值转换
    submitData.agreeProtocol = submitData.agreeProtocol ? 1 : 0;
    submitData.isSplit = submitData.isSplit ? 1 : 0;
    return submitData;
}

const submitForm = async () => {
    try {
        // 手动校验表单
        const isValid = validateForm();
        if (!isValid) {
            return; // 校验失败，直接返回
        }
        // 准备提交数据（包含时间转换）
        const submitData = prepareSubmitData();
        const { code, msg } = await ReservationRecordApi.create(submitData);
        if (code === 0) {
            sheep.$helper.toast('订单创建成功');
            sheep.$router.back();
        } else {
            sheep.$helper.toast(msg || '创建失败');
        }
    } catch (e) {
        console.error('表单提交错误:', e);
        sheep.$helper.toast('提交失败，请重试');
    }
};

// 其他方法保持不变
const productionCycle = ref(0)

const onCellProductChange = (e) => {
    if (e) {
        const product = state.cellList.find(item => item.id === e)
        if (product) {
            state.specificationList = specificationListAll.value.filter(item =>
                product.specifications.includes(item.value)
            ).map(item => ({
                value: item.value,
                text: item.label
            }))
            productionCycle.value = product.productionCycle || 0
        } else {
            state.specificationList = specificationListAll.value.map(item => ({
                value: item.value,
                text: item.label
            }))
            productionCycle.value = 0
        }
    }
    state.formData.cellSpecification = ''
}

// 计算最早可选时间 = 当前时间 + 生产周期天数
const minUsageTime = computed(() => {
    const now = new Date()
    now.setDate(now.getDate() + (productionCycle.value || 0))
    return now.toISOString().slice(0, 19).replace('T', ' ') // 格式化成 yyyy-MM-dd HH:mm:ss
})

function onProtocol(title) {
    closeAuthModal();
    sheep.$router.go('/pages/public/richtext', {
        title,
    });
}

//查询细胞列表
const getCellList = async () => {
    try {
        const { code, data } = await ReservationRecordApi.getCellPage({
            page: 1,
            pageSize: -1,
            status:0
        });
        if (code === 0) {
            state.cellList = data.list;
            state.cellProductOptions = data.list.map(item => ({
                value: item.id,
                text: item.productName
            }))
            console.log(state.cellProductOptions)
        } else {
            sheep.$helper.toast('查询失败');
        }
    } catch (e) {
        console.error(e);
    }
}

const specificationListAll = ref([])

async function getSpecificationListAll() {
    let { code, data } = await DictApi.getDictDataListByType('cell_specification');
    if (code !== 0) {
        return;
    }
    if (data && data.length > 0) {
        specificationListAll.value = data;
    }
}

watch(
    () => [state.formData.cellSpecification, state.formData.bagCount, state.formData.isSplit],
    ([spec, count, isSplit]) => {
        console.log(spec,count,isSplit)
        if (!spec || !count) {
            state.formData.totalCells = '';
            return;
        }

        const parts = spec.split(/×|x/); // 兼容 × 和 x
        if (parts.length !== 2) {
            state.formData.totalCells = spec;
            return;
        }

        const base = parseFloat(parts[0]);
        const exponent = parts[1];

        if (isNaN(base)) {
            state.formData.totalCells = '';
            return;
        }

        const totalBase = isSplit ? base : base * count;
        const totalBaseStr = Number.isInteger(totalBase) ? totalBase : totalBase.toFixed(2);

        state.formData.totalCells = `${totalBaseStr}×${exponent}`;
    },
    { immediate: true }
);
const getUserInfo = async () => {
    // 个人信息
    const userInfo = await sheep.$store('user').getInfo();
    if (userInfo) {
        state.formData.signerName = userInfo.nickname;
        state.formData.signerContact = userInfo.mobile;
    }
};
const getUserList = async () =>{
    let { code, data } = await CustomerApi.getCustomerPage({
        pageNo: 1,
        pageSize: -1,
    });
    state.customerList = data.list
}


onLoad(async () => {
    await getUserInfo()
    await  getUserList()
    await  getCellList()
    await  getSpecificationListAll()
});
</script>

<style lang="scss" scoped>
.flex-row {
    display: flex;
    gap: 10rpx;
}

.choose-btn {
    background-color: #007aff;
    color: #fff;
    font-size: 26rpx;
    padding: 0 20rpx;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
}

.popup-container {
    background: #fff;
    padding: 20rpx;
    border-radius: 20rpx 20rpx 0 0;
}

.popup-title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
}

.popup-item {
    padding: 20rpx;
    border-bottom: 1px solid #f5f5f5;
}
.popup-item:active {
    background: #f0f0f0;
}
.form-container {
    padding: 20rpx;
    background-color: #fff;
}
.fixed-bottom-bar {
    padding: 20rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 100;
}
.submit-btn {
    width: 100%;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 30rpx;
    color: #fff;
    background: linear-gradient(to right, #FF6000, #FF8C00);
    border: none;
}

/* Vue 3 深度选择器语法 */
:deep(.uni-select) {
    height: 72rpx !important;
}

:deep(.uni-select__input-text),
:deep(.uni-select__input-placeholder) {
    font-size: 28rpx !important;
    line-height: 72rpx !important;
    height: 72rpx !important;
}

:deep(.uni-easyinput__content) {
    height: 72rpx !important;
    padding-left: 20rpx !important;
}

:deep(.uni-input-input),
:deep(.uni-easyinput__placeholder) {
    padding-left: 20rpx !important;
    font-size: 28rpx !important;
    line-height: 72rpx !important;
    height: 72rpx !important;
}
</style>
